define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    // 二维码生成工具
    var QRCodeGenerator = {
        // 生成二维码图片URL
        getQRCodeUrl: function(text, size) {
            if (!text || text.trim() === '') return '';
            var encodedText = encodeURIComponent(text);
            
            // 使用相对路径，自动适应当前域名
            return `/qrcode/build?size=${size}x${size}&data=${encodedText}&margin=10`;
            
            // 或者使用当前站点的域名
            // var currentDomain = window.location.origin;
            // return `${currentDomain}/qrcode/build?size=${size}x${size}&data=${encodedText}&margin=10`;
        },
        
        // 显示二维码模态框
        showModal: function(text) {
            if (!text || text.trim() === '') {
                if (typeof Toastr !== 'undefined') {
                    Toastr.error('无效的运单号');
                }
                return;
            }
            
            var $template = $('#qrcodeModalTemplate');
            var $modal = $template.clone().removeAttr('id').appendTo('body');
            var $loading = $modal.find('.qrcode-loading');
            var $img = $modal.find('.qrcode-large');
            var $error = $modal.find('.qrcode-error');
            
            // 显示运单号
            $modal.find('.tracking-number').text(text);
            
            // 显示模态框
            $modal.modal('show');
            
            // 加载二维码
            $img.attr('src', this.getQRCodeUrl(text, 200))
                .on('load', function() {
                    $loading.hide();
                    $img.show();
                    $error.hide();
                })
                .on('error', function() {
                    $loading.hide();
                    $img.hide();
                    $error.show();
                });
            
            // 复制功能
            $modal.find('.btn-copy').on('click', function() {
                var $temp = $('<input>');
                $('body').append($temp);
                $temp.val(text).select();
                document.execCommand('copy');
                $temp.remove();
                
                if (typeof Toastr !== 'undefined') {
                    Toastr.success('已复制运单号');
                }
            });
            
            // 清理
            $modal.on('hidden.bs.modal', function() {
                $modal.remove();
            });
        },
        
        // HTML转义
        escapeHtml: function(text) {
            var div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
    };

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'order/index' + location.search,
                    add_url: 'order/add',
                    edit_url: 'order/edit',
                    del_url: 'order/del',
                    multi_url: 'order/multi',
                    import_url: 'order/import',
                    table: 'order',
                }
            });

            // 备份原始Table.api.formatter.operate函数以备使用
            var _original_operate_formatter = Table.api.formatter.operate;

            // 重写operate formatter
            Table.api.formatter.operate = function (value, row, index) {
                // 获取表格对象
                var table = this.table;
                var options = table ? table.bootstrapTable('getOptions') : {};
                var buttons = [];
                
                // 判断是否显示编辑按钮
                if (options.extend.edit_url) {
                    var editUrl = Table.api.replaceurl(options.extend.edit_url, {ids: row[options.pk]});
                    buttons.push({
                        name: 'edit',
                        icon: 'fa fa-pencil',
                        title: __('Edit'),
                        extend: 'data-toggle="tooltip"',
                        classname: 'btn btn-xs btn-success btn-drawer-edit',
                        url: editUrl,
                        'data-id': row[options.pk]
                    });
                }
                
                // 判断是否显示删除按钮
                if (options.extend.del_url) {
                    var delUrl = Table.api.replaceurl(options.extend.del_url, {ids: row[options.pk]});
                    buttons.push({
                        name: 'del',
                        icon: 'fa fa-trash',
                        title: __('Del'),
                        extend: 'data-toggle="tooltip"',
                        classname: 'btn btn-xs btn-danger btn-delone',
                        url: delUrl,
                        'data-id': row[options.pk]
                    });
                }
                
                // 构建按钮HTML
                var html = '<div class="btn-group-horizontal">';
                buttons.forEach(function (button) {
                    var attr = '';
                    for (var key in button) {
                        if (key !== 'name' && key !== 'icon' && key !== 'title' && key !== 'classname' && key !== 'url') {
                            attr += ' ' + key + '="' + button[key] + '"';
                        }
                    }
                    html += '<a href="javascript:;" class="' + button.classname + '" ' + attr + ' data-url="' + button.url + '" title="' + button.title + '"><i class="' + button.icon + '"></i></a>';
                });
                html += '</div>';
                
                // 添加样式
                html += `
                <style>
                .btn-group-horizontal {
                    display: inline-flex;
                    gap: 5px;
                }
                .btn-group-horizontal .btn {
                    float: none;
                    position: relative;
                    margin: 0;
                }
                .btn-group-horizontal .btn:not(:first-child):not(:last-child) {
                    border-radius: 3px;
                }
                .btn-group-horizontal .btn:first-child {
                    border-radius: 3px;
                }
                .btn-group-horizontal .btn:last-child {
                    border-radius: 3px;
                }
                </style>`;
                
                return html;
            };

            // 二维码格式化函数
            function qrCodeFormatter(value, row, index) {
                if (value && value.trim() !== '') {
                    var displayText = value.length > 8 ? value.substring(0, 5) + '...' : value;
                    
                    return `
                        <div class="qrcode-container" title="运单号: ${QRCodeGenerator.escapeHtml(value)}" 
                             onclick="QRCodeGenerator.showModal('${QRCodeGenerator.escapeHtml(value).replace(/'/g, "\\'")}')">
                            <div class="qrcode-loading">
                                <div class="qrcode-loading-spinner"></div>
                            </div>
                            <img src="${QRCodeGenerator.getQRCodeUrl(value, 40)}" 
                                 class="qrcode-img"
                                 onload="this.style.display='block'; this.previousElementSibling.style.display='none'"
                                 onerror="this.style.display='none'; this.previousElementSibling.style.display='none'; this.nextElementSibling.style.display='flex'">
                            <div class="qrcode-error">ERROR</div>
                            <div class="qrcode-text">${displayText}</div>
                        </div>
                    `;
                }
                return '<span class="text-muted">暂无数据</span>';
            }

            // 空数据格式化函数
            function emptyDataFormatter(value, row, index) {
                if (value === null || value === undefined) {
                    return '<span class="text-muted">暂无数据</span>';
                }
                return value && value.toString().trim() !== '' ? value : '<span class="text-muted">暂无数据</span>';
            }

            // 订单号点击处理函数
            function orderNumberFormatter(value, row, index) {
                if (!value || value.trim() === '') {
                    return '<span class="text-muted">暂无数据</span>';
                }
                
                return `<a href="javascript:;" class="order-detail-link" data-id="${row.id}" title="点击查看详情">${value}</a>`;
            }

            // 工程师选择器格式化函数
            function engineerFormatter(value, row, index) {
                if (value === null || value === undefined) {
                    value = '';
                }
                
                var html = `
                <a href="javascript:;" class="btn-change-engineer" data-id="${row.id}" data-toggle="tooltip" title="点击分配工程师">
                    ${value ? value : '<i class="fa fa-user-plus"></i> 选择工程师'}
                </a>`;
                
                return html;
            }

            // 修改标签格式化函数
            function tagFormatter(value, row, index) {
                if (!value || value.trim() === '') {
                    return '<span class="text-muted">暂无数据</span>';
                }
                
                // 分割标签
                var tags = value.split(',').filter(tag => tag.trim() !== '');
                
                if (tags.length === 0) {
                    return '<span class="text-muted">暂无数据</span>';
                }
                
                // 生成标签HTML
                var html = '<div class="tag-group">';
                tags.forEach(function(tag) {
                    html += `<span class="label label-info tag-item">${tag.trim()}</span>`;
                });
                html += '</div>';
                
                // 添加样式
                html += `
                <style>
                .tag-group {
                    display: inline-flex;
                    flex-wrap: wrap;
                    gap: 4px;
                }
                .tag-item {
                    display: inline-block;
                    padding: 2px 6px;
                    font-size: 12px;
                    font-weight: normal;
                    line-height: 1.4;
                    border-radius: 3px;
                    background-color: #e8f0fe;
                    color: #1a73e8;
                    margin: 0;
                    white-space: nowrap;
                }
                </style>`;
                
                return html;
            }

            // 工单状态格式化函数
            function workOrderStatusFormatter(value, row, index) {
                // 判断值是否为空或未定义
                var statusText = value ? value : '暂未完工';
                var statusClass = '';
                
                // 根据状态设置不同的样式
                if (statusText === '已完工') {
                    statusClass = 'success';
                } else if (statusText === '暂未完工' || statusText === '未完工') {
                    statusClass = 'warning';
                }
                
                // 生成标签
                return `
                <a href="javascript:;" class="label label-${statusClass} work-status-label" 
                   data-id="${row.id}" 
                   data-status="${statusText}"
                   onclick="showWorkStatusModal(${row.id}, '${statusText}')"
                   style="cursor:pointer">
                    ${statusText}
                </a>`;
            }

            // 结算金额格式化函数 - 支持行内编辑
            function settlementFormatter(value, row, index) {
                var isCompleted = row['工单状态'] === '已完工';
                var displayValue = value ? value : '0';
                
                if (isCompleted) {
                    return `<div class="settlement-amount">
                        <span class="settlement-display" data-id="${row.id}" data-value="${displayValue}">${displayValue}</span>
                        <div class="settlement-edit" style="display:none;">
                            <input type="number" class="form-control input-sm settlement-input" value="${displayValue}">
                            <div class="edit-actions">
                                <a href="javascript:;" class="btn btn-xs btn-success settlement-save"><i class="fa fa-check"></i></a>
                                <a href="javascript:;" class="btn btn-xs btn-default settlement-cancel"><i class="fa fa-times"></i></a>
                            </div>
                        </div>
                    </div>
                    <style>
                        .settlement-amount {
                            position: relative;
                        }
                        .settlement-display {
                            cursor: pointer;
                            padding: 2px 5px;
                            border-radius: 3px;
                            transition: all 0.2s;
                        }
                        .settlement-display:hover {
                            background-color: #f5f5f5;
                        }
                        .settlement-edit {
                            margin-top: 5px;
                        }
                        .edit-actions {
                            margin-top: 5px;
                            display: flex;
                            gap: 5px;
                        }
                        .settlement-input {
                            width: 100%;
                        }
                    </style>`;
                } else {
                    return value ? value : '<span class="text-muted">暂无数据</span>';
                }
            }

            // 添加信息员备注格式化函数
            function remarkFormatter(value, row, index) {
                var displayValue = value || '';
                var displayHtml = value ? value : '<span class="text-muted">暂无数据</span>';
                
                return `
                <div class="remark-container">
                    <span class="remark-display" data-id="${row.id}" data-value="${displayValue}">${displayHtml}</span>
                    <div class="remark-edit" style="display:none;">
                        <textarea class="form-control input-sm remark-input" rows="3" placeholder="请输入备注信息">${displayValue}</textarea>
                        <div class="edit-actions">
                            <a href="javascript:;" class="btn btn-xs btn-success remark-save"><i class="fa fa-check"></i></a>
                            <a href="javascript:;" class="btn btn-xs btn-default remark-cancel"><i class="fa fa-times"></i></a>
                        </div>
                    </div>
                </div>
                <style>
                    .remark-container {
                        position: relative;
                    }
                    .remark-display {
                        cursor: pointer;
                        padding: 5px 8px;
                        border-radius: 4px;
                        display: inline-block;
                        transition: all 0.3s;
                        width: 100%;
                        word-break: break-all;
                        min-height: 28px;
                        position: relative;
                    }
                    .remark-display:hover {
                        background-color: #f0f7ff;
                        box-shadow: 0 1px 3px rgba(0,0,0,0.05);
                    }
                    .remark-display:after {
                        content: "\\f044";
                        font-family: FontAwesome;
                        position: absolute;
                        right: 5px;
                        top: 5px;
                        font-size: 12px;
                        color: #3a86ff;
                        opacity: 0;
                        transition: opacity 0.3s;
                    }
                    .remark-display:hover:after {
                        opacity: 1;
                    }
                    .remark-edit {
                        margin-top: 8px;
                    }
                    .edit-actions {
                        margin-top: 8px;
                        display: flex;
                        gap: 8px;
                        justify-content: flex-end;
                    }
                    .remark-input {
                        width: 100%;
                        min-height: 80px;
                        resize: vertical;
                        border-color: #dbeafe;
                        box-shadow: 0 0 0 3px rgba(59,130,246,0.1);
                        transition: all 0.3s;
                    }
                    .remark-input:focus {
                        border-color: #3b82f6;
                        box-shadow: 0 0 0 3px rgba(59,130,246,0.2);
                    }
                    .remark-save {
                        box-shadow: 0 2px 5px rgba(0,0,0,0.1);
                        transition: all 0.3s;
                    }
                    .remark-save:hover {
                        transform: translateY(-1px);
                        box-shadow: 0 4px 8px rgba(0,0,0,0.12);
                    }
                </style>`;
            }

            // 定义收货人电话格式化函数
            function receiverPhoneFormatter(value, row, index) {
                // 首先尝试显示虚拟电话
                if (value && value.toString().trim() !== '') {
                    return value;
                }
                
                // 虚拟电话为空，尝试显示收货人电话1
                if (row['收货人电话1'] && row['收货人电话1'].toString().trim() !== '') {
                    return `<span class="text-muted">${row['收货人电话1']} (电话1)</span>`;
                }
                
                // 电话1也为空，尝试显示收货人电话2
                if (row['收货人电话2'] && row['收货人电话2'].toString().trim() !== '') {
                    return `<span class="text-muted">${row['收货人电话2']} (电话2)</span>`;
                }
                
                // 所有电话都为空
                return '<span class="text-muted">暂无联系方式</span>';
            }

            var table = $("#table");

            // 在Controller.index函数中，初始化表格配置之前添加一个请求标志
            var isTableLoading = false;

            // 修改表格初始化代码
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                pageSize: 10,
                pageList: [10, 25, 50, 100],
                pagination: true,
                sidePagination: 'server',
                
                // 添加ajaxOptions配置，解决多次请求和中断问题
                ajaxOptions: {
                    // 添加请求拦截器
                    beforeSend: function(xhr) {
                        if (isTableLoading) {
                            xhr.abort(); // 如果已经有请求在进行中，中止这个新请求
                            return false;
                        }
                        isTableLoading = true;
                    },
                    // 请求完成后处理
                    complete: function() {
                        isTableLoading = false;
                    }
                },
                
                // 加强错误处理
                onLoadError: function(status, jqXHR) {
                    if (status === 0) {
                        // 忽略中断的请求，不显示错误信息
                        console.log('请求被中断，这是正常的');
                        return;
                    }
                    console.error('加载数据失败:', status);
                },
                
                formatNoMatches: function() {
                    return '没有找到匹配的记录';
                },
                formatLoadingMessage: function() {
                    return '正在努力地加载数据中，请稍候……';
                },
                responseHandler: function(res) {
                    if (res && typeof res === 'object') {
                        if (!res.hasOwnProperty('rows') || !res.hasOwnProperty('total')) {
                            return {
                                total: res.total || 0,
                                rows: res.rows || []
                            };
                        }
                        return res;
                    } else {
                        console.error('API返回了无效数据:', res);
                        return {
                            total: 0,
                            rows: []
                        };
                    }
                },
                columns: [
                    [
                        {checkbox: true},
                        // {field: 'id', title: __('Id')},
                        {field: '订单号', title: __('订单号'), operate: 'LIKE', formatter: orderNumberFormatter, width: '30%', resizable: true},
                        {field: '标签', title: __('标签'), operate: 'LIKE', formatter: tagFormatter, width: '15%', resizable: true},
                        {field: '收货人名称', title: __('收货人'), operate: 'LIKE', formatter: emptyDataFormatter, width: '25%', resizable: true},
                        
                        {field: '收货人虚拟电话', title: __('联系电话'), operate: 'LIKE', formatter: receiverPhoneFormatter, width: '20%', resizable: true},
                        {field: '收货人详细地址', title: __('地址'), operate: 'LIKE', formatter: emptyDataFormatter, width: '25%', resizable: true},
                        
                        {field: '业务类型', title: __('业务类型'), operate: 'LIKE', formatter: emptyDataFormatter, width: '15%', resizable: true},
                        {field: '配送工程师', title: __('配送工程师'), operate: 'LIKE', formatter: engineerFormatter, width: '15%', resizable: true},
                        {field: '品类', title: __('品类'), operate: 'LIKE', formatter: emptyDataFormatter, width: '15%', resizable: true},
                        {field: '信息员备注', title: __('信息员备注'), operate: 'LIKE', formatter: remarkFormatter, width: '15%', resizable: true},
                        
                        {field: '工单状态', title: __('工单状态'), operate: 'LIKE', formatter: workOrderStatusFormatter, width: '10%', resizable: true},
                        {field: '结算金额', title: __('结算金额'), operate: 'LIKE', formatter: settlementFormatter, width: '10%', resizable: true},
                        {field: '运单号', title: __('运单号'), operate: 'LIKE', formatter: qrCodeFormatter, width: '10%', resizable: true},
                        
                        
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate, width: '20%', resizable: true}
                    ]
                ]
            });

            // 延迟初始化固定列
            setTimeout(function() {
                // 确保其他插件初始化完成后再重置视图
                table.bootstrapTable('resetView');
            }, 300);

            // 在表格初始化完成后，绑定刷新事件
            table.on('refresh.bs.table', function() {
                isTableLoading = false; // 确保刷新前重置状态
            });

            // 使用静默刷新减少不必要的请求
            $(window).resize(function() {
                if (table.data('bootstrap.table')) {
                    table.bootstrapTable('resetView', {silent: true});
                }
            });

            // 修改load-success事件处理
            table.on('load-success.bs.table', function(e, data) {
                // 重置加载状态
                isTableLoading = false;
                
                // 处理数据验证
                if (!data || !data.rows) {
                    table.bootstrapTable('removeAll');
                    table.bootstrapTable('updateFormatText', 'formatNoMatches', '暂无数据');
                }
                
                // 确保在表格外部隐藏加载指示器
                $('.fixed-table-loading').hide();
                
                // 如果有自定义过滤器的代码，将其移到这里
                try {
                    // 获取当前的过滤器选项
                    var options = table.bootstrapTable('getOptions');
                    
                    // 检查filterOptions是否存在，不存在则创建
                    if (!options.filterOptions) {
                        options.filterOptions = {};
                    }
                    
                    // 保存原始的过滤器函数或创建一个默认的
                    var originalFilter = options.filterOptions.filterAlgorithm || function(row, filters) {
                        return true; // 默认过滤器，接受所有行
                    };
                    
                    // 替换为自定义的过滤器函数
                    options.filterOptions.filterAlgorithm = function(row, filters) {
                        // 如果没有搜索电话字段，使用原始过滤
                        if (!filters || !filters['收货人虚拟电话']) {
                            return originalFilter(row, filters);
                        }
                        
                        // 提取搜索关键字
                        var keyword = filters['收货人虚拟电话'].toLowerCase();
                        
                        // 在三个电话字段中搜索
                        var virtualPhone = (row['收货人虚拟电话'] || '').toString().toLowerCase();
                        var phone1 = (row['收货人电话1'] || '').toString().toLowerCase();
                        var phone2 = (row['收货人电话2'] || '').toString().toLowerCase();
                        
                        // 任何一个电话字段包含关键字则匹配成功
                        if (virtualPhone.indexOf(keyword) > -1 || 
                            phone1.indexOf(keyword) > -1 || 
                            phone2.indexOf(keyword) > -1) {
                            return true;
                        }
                        
                        // 如果电话字段不匹配，还需检查其他过滤条件
                        delete filters['收货人虚拟电话'];
                        var result = originalFilter(row, filters);
                        filters['收货人虚拟电话'] = keyword; // 恢复过滤条件
                        return result;
                    };
                } catch (error) {
                    console.error('自定义过滤器出错:', error);
                }
            });

            // 防止同时发出多个请求
            $(document).on('click', '.btn-refresh', function(e) {
                if (isTableLoading) {
                    e.preventDefault();
                    e.stopPropagation();
                    return false;
                }
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
            
            // 点击订单号显示抽屉详情
            $(document).on('click', '.order-detail-link', function() {
                var id = $(this).data('id');
                Controller.api.showDetail(id);
            });
            
            // 将QRCodeGenerator暴露到全局
            window.QRCodeGenerator = QRCodeGenerator;

            // 覆盖默认的事件处理
            Table.api.events.operate = {
                'click .btn-drawer-edit': function (e, value, row, index) {
                    e.stopPropagation();
                    var id = $(this).data('id');
                    var url = $(this).data('url');
                    Controller.api.showEditDrawer(id, url);
                    return false;
                },
                'click .btn-delone': function (e, value, row, index) {
                    e.stopPropagation();
                    var that = this;
                    var top = $(that).offset().top - $(window).scrollTop();
                    var left = $(that).offset().left - $(window).scrollLeft() - 260;
                    if (top + 154 > $(window).height()) {
                        top = top - 154;
                    }
                    if ($(window).width() < 480) {
                        top = left = undefined;
                    }
                    var id = $(this).data('id');
                    var url = $(this).data('url');
                    Layer.confirm(
                        __('Are you sure you want to delete this item?'),
                        {icon: 3, title: __('Warning'), offset: [top, left], shadeClose: true},
                        function (index) {
                            Fast.api.ajax({
                                url: url,
                                data: {ids: id}
                            }, function (data, ret) {
                                Layer.close(index);
                                if (ret.code === 1) {
                                    $(that).closest('table').bootstrapTable('refresh');
                                }
                            });
                        }
                    );
                    return false;
                }
            };

            // 在表格初始化后添加事件绑定
            $(document).off('click', '.btn-drawer-edit').on('click', '.btn-drawer-edit', function(e) {
                e.preventDefault();
                e.stopPropagation();
                var id = $(this).data('id');
                var url = $(this).data('url');
                Controller.api.showEditDrawer(id, url);
                return false;
            });

            // 刷新表格时重新绑定按钮事件
            table.on('post-body.bs.table', function () {
                $('.btn-edit').each(function() {
                    $(this).removeClass('btn-edit').addClass('btn-drawer-edit');
                });
            });

            // 单个分配工程师
            $(document).on('click', '.btn-change-engineer', function() {
                var id = $(this).data('id');
                Controller.api.showEngineerSelector([id], function(engineer) {
                    // 刷新表格
                    $("#table").bootstrapTable('refresh');
                });
            });

            // 批量分配工程师
            $(document).on('click', '.btn-assign-engineer', function() {
                var ids = Table.api.selectedids(table);
                if (ids.length === 0) {
                    Layer.alert('请选择要分配的订单');
                    return;
                }
                Controller.api.showEngineerSelector(ids, function(engineer) {
                    // 刷新表格
                    $("#table").bootstrapTable('refresh');
                });
            });

            // 批量修改工单状态
            $(document).on('click', '.btn-batch-status', function() {
                var ids = Table.api.selectedids(table);
                if (ids.length === 0) {
                    Layer.alert('请选择要修改的订单');
                    return;
                }
                
                // 显示批量修改状态模态框
                showBatchWorkStatusModal(ids);
            });

            // 行内编辑结算金额
            $(document).on('click', '.settlement-display', function() {
                var $this = $(this);
                var $container = $this.closest('.settlement-amount');
                $this.hide();
                $container.find('.settlement-edit').show();
            });

            $(document).on('click', '.settlement-save', function() {
                var $container = $(this).closest('.settlement-amount');
                var id = $container.find('.settlement-display').data('id');
                var newValue = $container.find('.settlement-input').val();
                
                // 发送请求更新结算金额
                Fast.api.ajax({
                    url: 'order/updateSettlement',
                    type: 'POST',
                    data: {
                        id: id,
                        amount: newValue
                    }
                }, function(data, ret) {
                    // 更新显示
                    $container.find('.settlement-display').text(newValue).data('value', newValue);
                    $container.find('.settlement-display').show();
                    $container.find('.settlement-edit').hide();
                    
                    // 添加成功提示效果
                    var $display = $container.find('.settlement-display');
                    $display.css({
                        'background-color': '#ecfdf5',
                        'border-left': '3px solid #10b981',
                        'padding': '5px 8px'
                    });
                    setTimeout(function() {
                        $display.css({
                            'background-color': '',
                            'border-left': '',
                            'padding': '2px 5px'
                        });
                    }, 2000);
                    
                    return false;
                });
            });

            $(document).on('click', '.settlement-cancel', function() {
                var $container = $(this).closest('.settlement-amount');
                $container.find('.settlement-display').show();
                $container.find('.settlement-edit').hide();
            });

            // 为表格添加行选择变化事件，更新批量按钮状态
            table.on('check.bs.table uncheck.bs.table check-all.bs.table uncheck-all.bs.table', function () {
                var ids = Table.api.selectedids(table);
                $('.btn-batch-status').toggleClass('disabled', !ids.length);
            });

            // 批量修改工单状态的模态框
            window.showBatchWorkStatusModal = function(ids) {
                // 移除已存在的模态框
                $("#batchWorkStatusModal").remove();
                
                // 创建模态框
                var modalHtml = `
                <div class="modal fade" id="batchWorkStatusModal" tabindex="-1" role="dialog">
                    <div class="modal-dialog modal-sm" role="document">
                        <div class="modal-content">
                            <div class="modal-header">
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                    <span aria-hidden="true">&times;</span>
                                </button>
                                <h4 class="modal-title">
                                    <i class="fa fa-tasks"></i> 批量修改工单状态
                                </h4>
                            </div>
                            <div class="modal-body">
                                <p class="text-muted">已选择 ${ids.length} 个工单</p>
                                <div class="status-options">
                                    <div class="status-option" data-status="未完工">
                                        <i class="fa fa-circle-o"></i>
                                        <span>未完工</span>
                                    </div>
                                    <div class="status-option" data-status="已完工">
                                        <i class="fa fa-check-circle-o"></i>
                                        <span>已完工</span>
                                    </div>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                                <button type="button" class="btn btn-primary" id="confirmBatchStatusChange" disabled>确认</button>
                            </div>
                        </div>
                    </div>
                </div>`;
                
                // 添加样式
                var modalStyle = `
                <style id="batchWorkStatusModalStyle">
                    #batchWorkStatusModal .modal-content {
                        border-radius: 8px;
                        box-shadow: 0 5px 15px rgba(0,0,0,0.1);
                    }
                    
                    #batchWorkStatusModal .modal-header {
                        padding: 15px 20px;
                        background: #f8f9fa;
                        border-bottom: 1px solid #edf2f9;
                        border-radius: 8px 8px 0 0;
                    }
                    
                    #batchWorkStatusModal .modal-title {
                        font-size: 16px;
                        color: #2c3e50;
                        font-weight: 600;
                    }
                    
                    #batchWorkStatusModal .modal-title i {
                        margin-right: 8px;
                        color: #3a86ff;
                    }
                    
                    #batchWorkStatusModal .modal-body {
                        padding: 20px;
                    }
                    
                    .status-options {
                        display: flex;
                        flex-direction: column;
                        gap: 12px;
                        margin-top: 15px;
                    }
                    
                    .status-option {
                        display: flex;
                        align-items: center;
                        padding: 12px;
                        border-radius: 6px;
                        border: 1px solid #edf2f9;
                        cursor: pointer;
                        transition: all 0.2s ease;
                    }
                    
                    .status-option:hover {
                        background-color: #f8f9fa;
                        transform: translateY(-2px);
                    }
                    
                    .status-option.active {
                        background-color: #e8f0fe;
                        border-color: #3a86ff;
                    }
                    
                    .status-option i {
                        font-size: 18px;
                        margin-right: 10px;
                    }
                    
                    .status-option:first-child i {
                        color: #ffc107;
                    }
                    
                    .status-option:last-child i {
                        color: #28a745;
                    }
                    
                    .status-option span {
                        font-size: 14px;
                        color: #2c3e50;
                    }
                </style>`;
                
                // 添加到页面
                $(modalHtml).appendTo('body');
                $(modalStyle).appendTo('head');
                
                // 显示模态框
                $("#batchWorkStatusModal").modal('show');
                
                // 添加选项点击事件
                $(".status-option").on('click', function() {
                    $(".status-option").removeClass('active');
                    $(this).addClass('active');
                    $("#confirmBatchStatusChange").prop('disabled', false);
                });
                
                // 确认按钮点击事件
                $("#confirmBatchStatusChange").on('click', function() {
                    var status = $(".status-option.active").data('status');
                    
                    Fast.api.ajax({
                        url: 'order/batchUpdateWorkStatus',
                        type: 'POST',
                        data: {
                            ids: ids.join(','),
                            status: status
                        }
                    }, function(data, ret) {
                        // 添加更明显的成功提示
                        Toastr.success('已成功更新 ' + ids.length + ' 个工单状态为：' + status);
                        
                        // 关闭模态框
                        $("#batchWorkStatusModal").modal('hide');
                        
                        // 刷新表格
                        $("#table").bootstrapTable('refresh');
                        return false;
                    });
                });
            };

            // 在表格初始化后添加信息员备注的事件处理代码
            $(document).on('click', '.remark-display', function() {
                var $this = $(this);
                var $container = $this.closest('.remark-container');
                $this.hide();
                $container.find('.remark-edit').show();
                // 自动聚焦输入框
                $container.find('.remark-input').focus();
            });

            $(document).on('click', '.remark-save', function() {
                var $container = $(this).closest('.remark-container');
                var id = $container.find('.remark-display').data('id');
                var newValue = $container.find('.remark-input').val().trim();
                
                // 显示加载状态
                var $btn = $(this);
                var $icon = $btn.find('i');
                var originalClass = $icon.attr('class');
                $icon.attr('class', 'fa fa-spinner fa-spin');
                $btn.attr('disabled', true);
                
                // 发送请求更新信息员备注
                Fast.api.ajax({
                    url: 'order/updateRemark',
                    type: 'POST',
                    data: {
                        id: id,
                        remark: newValue
                    }
                }, function(data, ret) {
                    // 恢复按钮状态
                    $icon.attr('class', originalClass);
                    $btn.attr('disabled', false);
                    
                    // 更新显示内容
                    var displayHtml = newValue ? newValue : '<span class="text-muted">暂无数据</span>';
                    $container.find('.remark-display').html(displayHtml).data('value', newValue);
                    $container.find('.remark-display').show();
                    $container.find('.remark-edit').hide();
                    
                    // 添加成功提示效果
                    var $display = $container.find('.remark-display');
                    $display.css({
                        'background-color': '#ecfdf5',
                        'border-left': '3px solid #10b981'
                    });
                    setTimeout(function() {
                        $display.css({
                            'background-color': '',
                            'border-left': ''
                        });
                    }, 2000);
                    
                    return false;
                }, function(data, ret) {
                    // 请求失败时也恢复按钮状态
                    $icon.attr('class', originalClass);
                    $btn.attr('disabled', false);
                    return false;
                });
            });

            $(document).on('click', '.remark-cancel', function() {
                var $container = $(this).closest('.remark-container');
                $container.find('.remark-display').show();
                $container.find('.remark-edit').hide();
            });

            // 支持按下 ESC 键取消编辑，按下 Ctrl+Enter 保存
            $(document).on('keydown', '.remark-input', function(e) {
                if (e.key === 'Escape') {
                    // 按下 ESC 取消编辑
                    var $container = $(this).closest('.remark-container');
                    $container.find('.remark-display').show();
                    $container.find('.remark-edit').hide();
                } else if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {
                    // 按下 Ctrl+Enter 保存
                    $(this).closest('.remark-container').find('.remark-save').click();
                }
            });

            // 添加备注编辑模态框（可选，用于移动设备上更好的体验）
            window.showRemarkModal = function(id, value) {
                // 移除已存在的模态框
                $("#remarkModal").remove();
                
                // 创建模态框
                var modalHtml = `
                <div class="modal fade" id="remarkModal" tabindex="-1" role="dialog">
                    <div class="modal-dialog" role="document">
                        <div class="modal-content">
                            <div class="modal-header">
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                    <span aria-hidden="true">&times;</span>
                                </button>
                                <h4 class="modal-title">
                                    <i class="fa fa-edit"></i> 编辑信息员备注
                                </h4>
                            </div>
                            <div class="modal-body">
                                <textarea class="form-control modal-remark-input" rows="5" placeholder="请输入备注信息">${value || ''}</textarea>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                                <button type="button" class="btn btn-primary" id="saveModalRemark">保存</button>
                            </div>
                        </div>
                    </div>
                </div>`;
                
                // 添加到页面
                $(modalHtml).appendTo('body');
                
                // 显示模态框
                $("#remarkModal").modal('show');
                
                // 自动聚焦输入框
                $("#remarkModal").on('shown.bs.modal', function() {
                    $(this).find('.modal-remark-input').focus();
                });
                
                // 保存按钮点击事件
                $("#saveModalRemark").on('click', function() {
                    var newValue = $('.modal-remark-input').val().trim();
                    
                    Fast.api.ajax({
                        url: 'order/updateRemark',
                        type: 'POST',
                        data: {
                            id: id,
                            remark: newValue
                        }
                    }, function(data, ret) {
                        // 关闭模态框
                        $("#remarkModal").modal('hide');
                        
                        // 刷新表格
                        $("#table").bootstrapTable('refresh');
                        return false;
                    });
                });
            };

            // 在表格初始化前添加自定义搜索
            table.on('load-success.bs.table', function() {
                try {
                    // 获取当前的过滤器选项
                    var options = table.bootstrapTable('getOptions');
                    
                    // 检查filterOptions是否存在，不存在则创建
                    if (!options.filterOptions) {
                        options.filterOptions = {};
                    }
                    
                    // 保存原始的过滤器函数或创建一个默认的
                    var originalFilter = options.filterOptions.filterAlgorithm || function(row, filters) {
                        return true; // 默认过滤器，接受所有行
                    };
                    
                    // 替换为自定义的过滤器函数
                    options.filterOptions.filterAlgorithm = function(row, filters) {
                        // 如果没有搜索电话字段，使用原始过滤
                        if (!filters || !filters['收货人虚拟电话']) {
                            return originalFilter(row, filters);
                        }
                        
                        // 提取搜索关键字
                        var keyword = filters['收货人虚拟电话'].toLowerCase();
                        
                        // 在三个电话字段中搜索
                        var virtualPhone = (row['收货人虚拟电话'] || '').toString().toLowerCase();
                        var phone1 = (row['收货人电话1'] || '').toString().toLowerCase();
                        var phone2 = (row['收货人电话2'] || '').toString().toLowerCase();
                        
                        // 任何一个电话字段包含关键字则匹配成功
                        if (virtualPhone.indexOf(keyword) > -1 || 
                            phone1.indexOf(keyword) > -1 || 
                            phone2.indexOf(keyword) > -1) {
                            return true;
                        }
                        
                        // 如果电话字段不匹配，还需检查其他过滤条件
                        delete filters['收货人虚拟电话'];
                        var result = originalFilter(row, filters);
                        filters['收货人虚拟电话'] = keyword; // 恢复过滤条件
                        return result;
                    };
                } catch (error) {
                    console.error('设置自定义过滤器时出错:', error);
                }
            });

            // 在表格加载完成时检查数据
            table.on('load-success.bs.table', function(e, data) {
                // 如果返回的数据格式不正确，手动处理
                if (!data || !data.rows) {
                    table.bootstrapTable('removeAll');
                    table.bootstrapTable('updateFormatText', 'formatNoMatches', '暂无数据');
                }
                
                // 检查空数据情况
                if (data && data.rows && data.rows.length === 0) {
                    // 确保表格显示"无数据"信息
                    var $tableBody = table.find('.fixed-table-body');
                    if ($tableBody.find('.no-records-found').length === 0) {
                        $tableBody.find('tbody').html('<tr class="no-records-found"><td colspan="' + 
                            table.find('th').length + '">没有找到匹配的记录</td></tr>');
                    }
                }
            });
        },
        
        api: {
            // 显示工单详情抽屉
            showDetail: function(id) {
                var layerIndex = Fast.api.open(
                    'order/detail?id=' + id, 
                    __('工单详情'), 
                    {
                        type: 2,
                        area: ['90%', '100%'],
                        offset: 'r',
                        maxmin: false,
                        scrollbar: false,
                        resize: false,
                        skin: 'layui-layer-adminRight',
                        shade: 0.3,
                        shadeClose: true
                    }
                );
            },
            
            // 显示编辑抽屉
            showEditDrawer: function(id, url) {
                var layerIndex = Fast.api.open(
                    url,
                    __('编辑订单'),
                    {
                        type: 2,
                        area: ['90%', '100%'],
                        offset: 'r',
                        maxmin: false,
                        scrollbar: false,
                        resize: false,
                        skin: 'layui-layer-adminRight',
                        shade: 0.3,
                        shadeClose: true
                    }
                );
                return layerIndex;
            },
            
            // 显示工程师选择器
            showEngineerSelector: function(orderIds, callback) {
                // 创建模态框结构
                var modalHtml = `
                <div class="modal fade modern-modal" id="engineerSelectorModal" tabindex="-1" role="dialog">
                    <div class="modal-dialog modal-lg" role="document">
                        <div class="modal-content">
                            <div class="modal-header">
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                    <span aria-hidden="true">&times;</span>
                                </button>
                                <h4 class="modal-title">
                                    <i class="fa fa-user-plus"></i> 选择配送工程师
                                    <small class="text-muted">请选择要分配的工程师</small>
                                </h4>
                            </div>
                            <div class="modal-body">
                                <div class="search-box">
                                    <div class="input-group">
                                        <div class="input-group-addon">
                                            <i class="fa fa-search"></i>
                                        </div>
                                        <input type="text" class="form-control" id="engineerSearch" placeholder="搜索工程师姓名、电话、区域或标签">
                                    </div>
                                </div>
                                <div class="engineer-list-container">
                                    <div class="text-center p-20">
                                        <i class="fa fa-spinner fa-spin fa-2x"></i>
                                        <p class="m-t-10">加载中...</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>`;

                // 添加样式
                var modalStyle = `
                <style id="engineerSelectorStyle">
                .modern-modal .modal-content {
                    border: none;
                    border-radius: 12px;
                    box-shadow: 0 8px 24px rgba(0,0,0,0.12);
                }

                .modern-modal .modal-header {
                    padding: 20px 25px;
                    background: #f8f9fa;
                    border-bottom: 1px solid #edf2f9;
                    border-radius: 12px 12px 0 0;
                }

                .modern-modal .modal-title {
                    font-size: 18px;
                    color: #2c3e50;
                    font-weight: 600;
                }

                .modern-modal .modal-title i {
                    margin-right: 10px;
                    color: #3a86ff;
                }

                .modern-modal .modal-title small {
                    font-size: 14px;
                    margin-left: 10px;
                    color: #95a5a6;
                    font-weight: normal;
                }

                .modern-modal .modal-body {
                    padding: 0;
                }

                .search-box {
                    padding: 20px 25px;
                    background: #fff;
                    border-bottom: 1px solid #edf2f9;
                }

                .search-box .input-group {
                    max-width: 100%;
                }

                .search-box .input-group-addon {
                    background: #f8f9fa;
                    border-color: #e9ecef;
                    color: #6c757d;
                }

                .search-box .form-control {
                    border-color: #e9ecef;
                    box-shadow: none;
                    height: 42px;
                    font-size: 14px;
                }

                .search-box .form-control:focus {
                    border-color: #3a86ff;
                    box-shadow: 0 0 0 3px rgba(58,134,255,0.1);
                }

                .engineer-list-container {
                    padding: 15px;
                    max-height: 60vh;
                    overflow-y: auto;
                    background: #fff;
                }

                .engineer-grid {
                    display: grid;
                    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
                    gap: 15px;
                    padding: 10px;
                }

                .engineer-card {
                    background: #fff;
                    border-radius: 10px;
                    padding: 20px;
                    transition: all 0.3s ease;
                    cursor: pointer;
                    border: 1px solid #edf2f9;
                    display: flex;
                    align-items: center;
                    gap: 15px;
                }

                .engineer-card:hover {
                    transform: translateY(-2px);
                    box-shadow: 0 4px 12px rgba(0,0,0,0.08);
                    border-color: #3a86ff;
                }

                .engineer-avatar {
                    width: 50px;
                    height: 50px;
                    background: #e8f1ff;
                    border-radius: 12px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    font-size: 24px;
                    color: #3a86ff;
                    flex-shrink: 0;
                }

                .engineer-info {
                    flex: 1;
                    min-width: 0;
                }

                .engineer-name {
                    font-size: 16px;
                    font-weight: 600;
                    color: #2c3e50;
                    margin: 0 0 5px;
                    white-space: nowrap;
                    overflow: hidden;
                    text-overflow: ellipsis;
                }

                .engineer-contact {
                    font-size: 13px;
                    color: #6c757d;
                    margin-bottom: 8px;
                    display: flex;
                    align-items: center;
                    gap: 5px;
                }

                .engineer-contact i {
                    font-size: 12px;
                }

                .engineer-tags {
                    display: flex;
                    flex-wrap: wrap;
                    gap: 6px;
                }

                .tag {
                    padding: 4px 8px;
                    border-radius: 6px;
                    font-size: 12px;
                    font-weight: 500;
                    white-space: nowrap;
                }

                .tag-area {
                    background: #e8f1ff;
                    color: #3a86ff;
                }

                .tag-skill {
                    background: #e9ecef;
                    color: #495057;
                }

                .p-20 {
                    padding: 20px;
                }

                .m-t-10 {
                    margin-top: 10px;
                }

                /* 自定义滚动条 */
                .engineer-list-container::-webkit-scrollbar {
                    width: 8px;
                }

                .engineer-list-container::-webkit-scrollbar-track {
                    background: #f8f9fa;
                }

                .engineer-list-container::-webkit-scrollbar-thumb {
                    background: #cfd8dc;
                    border-radius: 4px;
                }

                .engineer-list-container::-webkit-scrollbar-thumb:hover {
                    background: #b0bec5;
                }

                /* 响应式调整 */
                @media (max-width: 768px) {
                    .modern-modal .modal-dialog {
                        margin: 10px;
                    }
                    
                    .engineer-grid {
                        grid-template-columns: 1fr;
                    }
                    
                    .search-box {
                        padding: 15px;
                    }
                }
                </style>`;

                // 移除已存在的模态框和样式
                $("#engineerSelectorModal").remove();
                $("#engineerSelectorStyle").remove();
                
                // 添加新模态框和样式
                $(modalHtml).appendTo('body');
                $(modalStyle).appendTo('head');
                
                var $modal = $("#engineerSelectorModal");
                var $container = $modal.find('.engineer-list-container');
                var $search = $modal.find('#engineerSearch');
                
                // 显示模态框
                $modal.modal('show');
                
                // 加载工程师列表
                $.ajax({
                    url: 'order/getEngineers',
                    type: 'GET',
                    dataType: 'json',
                    success: function(ret) {
                        console.log('工程师数据:', ret.data); // 调试用
                        
                        if (!ret || ret.code !== 1 || !ret.data) {
                            $container.html('<div class="text-center p-20"><p>获取工程师数据失败</p></div>');
                            return;
                        }
                        
                        var engineers = ret.data;
                        
                        if (engineers.length === 0) {
                            $container.html('<div class="text-center p-20"><p>暂无工程师数据</p></div>');
                            return;
                        }
                        
                        // 渲染工程师列表
                        function renderEngineerList(data) {
                            var html = '<div class="engineer-grid">';
                            
                            data.forEach(function(engineer) {
                                // 处理标签
                                var tags = engineer.tags ? engineer.tags.split(',') : [];
                                var tagsHtml = tags.map(tag => 
                                    `<span class="tag tag-skill">${tag.trim()}</span>`
                                ).join('');
                                
                                html += `
                                <div class="engineer-card" data-id="${engineer.id}" data-name="${engineer.name}">
                                    <div class="engineer-avatar">
                                        <i class="fa fa-user"></i>
                                    </div>
                                    <div class="engineer-info">
                                        <h4 class="engineer-name">${engineer.name || '未命名'}</h4>
                                        <div class="engineer-contact">
                                            <i class="fa fa-phone"></i>
                                            <span>${engineer.mobile || '无联系方式'}</span>
                                        </div>
                                        <div class="engineer-tags">
                                            <span class="tag tag-area">${engineer.area || '未设置区域'}</span>
                                            ${tagsHtml}
                                        </div>
                                    </div>
                                </div>`;
                            });
                            
                            html += '</div>';
                            $container.html(html);
                            
                            // 绑定选择事件
                            $container.find('.engineer-card').on('click', function() {
                                var $this = $(this);
                                
                                // 添加选中效果
                                $this.addClass('selected')
                                    .siblings().removeClass('selected');
                                    
                                var engineerId = $this.data('id');
                                var engineerName = $this.data('name');
                                
                                // 调用分配工程师API
                                var isBatch = orderIds.length > 1;
                                var url = isBatch ? 'order/batchAssignEngineer' : 'order/assignEngineer';
                                var apiData = isBatch ? {
                                    ids: orderIds.join(','),
                                    engineer_id: engineerId
                                } : {
                                    id: orderIds[0],
                                    engineer_id: engineerId
                                };
                                
                                Fast.api.ajax({
                                    url: url,
                                    type: 'POST',
                                    data: apiData
                                }, function(result) {
                                    // 关闭模态框
                                    $modal.modal('hide');
                                    
                                    // 刷新表格
                                    $("#table").bootstrapTable('refresh');
                                    
                                    if (callback) {
                                        callback({
                                            id: engineerId,
                                            name: engineerName
                                        });
                                    }
                                    
                                    return true;
                                });
                            });
                        }
                        
                        // 初始渲染
                        renderEngineerList(engineers);
                        
                        // 绑定搜索事件
                        $search.on('input', function() {
                            var query = $(this).val().toLowerCase();
                            var filtered = engineers.filter(function(engineer) {
                                return (
                                    (engineer.name && engineer.name.toLowerCase().indexOf(query) !== -1) ||
                                    (engineer.mobile && engineer.mobile.toLowerCase().indexOf(query) !== -1) ||
                                    (engineer.area && engineer.area.toLowerCase().indexOf(query) !== -1) ||
                                    (engineer.tags && engineer.tags.toLowerCase().indexOf(query) !== -1)
                                );
                            });
                            renderEngineerList(filtered);
                        });
                    },
                    error: function(xhr, status, error) {
                        console.error('获取工程师数据失败:', error);
                        $container.html('<div class="text-center p-20"><p>获取工程师数据失败</p></div>');
                    }
                });
            },
            
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        },
        
        add: function () {
            Controller.api.bindevent();
        },
        
        edit: function () {
            Controller.api.bindevent();
        },
        
        detail: function() {
            Controller.api.bindevent();
        }
    };
    
    // 在Controller对象外部添加全局关闭抽屉方法
    window.closeOrderDrawer = function() {
        var layerIndex = top.layer.getFrameIndex(window.name);
        top.layer.close(layerIndex);
    };
    
    // 在Controller对象外部添加全局工单状态模态框显示方法
    window.showWorkStatusModal = function(id, currentStatus) {
        // 移除已存在的模态框
        $("#workStatusModal").remove();
        
        // 创建模态框
        var modalHtml = `
        <div class="modal fade" id="workStatusModal" tabindex="-1" role="dialog">
            <div class="modal-dialog modal-sm" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                        <h4 class="modal-title">
                            <i class="fa fa-tasks"></i> 修改工单状态
                        </h4>
                    </div>
                    <div class="modal-body">
                        <div class="status-options">
                            <div class="status-option ${currentStatus === '未完工' ? 'active' : ''}" data-status="未完工">
                                <i class="fa fa-circle-o"></i>
                                <span>未完工</span>
                            </div>
                            <div class="status-option ${currentStatus === '已完工' ? 'active' : ''}" data-status="已完工">
                                <i class="fa fa-check-circle-o"></i>
                                <span>已完工</span>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" id="confirmStatusChange">确认</button>
                    </div>
                </div>
            </div>
        </div>`;
        
        // 添加样式
        var modalStyle = `
        <style id="workStatusModalStyle">
            #workStatusModal .modal-content {
                border-radius: 8px;
                box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            }
            
            #workStatusModal .modal-header {
                padding: 15px 20px;
                background: #f8f9fa;
                border-bottom: 1px solid #edf2f9;
                border-radius: 8px 8px 0 0;
            }
            
            #workStatusModal .modal-title {
                font-size: 16px;
                color: #2c3e50;
                font-weight: 600;
            }
            
            #workStatusModal .modal-title i {
                margin-right: 8px;
                color: #3a86ff;
            }
            
            #workStatusModal .modal-body {
                padding: 20px;
            }
            
            .status-options {
                display: flex;
                flex-direction: column;
                gap: 12px;
            }
            
            .status-option {
                display: flex;
                align-items: center;
                padding: 12px;
                border-radius: 6px;
                border: 1px solid #edf2f9;
                cursor: pointer;
                transition: all 0.2s ease;
            }
            
            .status-option:hover {
                background-color: #f8f9fa;
                transform: translateY(-2px);
            }
            
            .status-option.active {
                background-color: #e8f0fe;
                border-color: #3a86ff;
            }
            
            .status-option i {
                font-size: 18px;
                margin-right: 10px;
            }
            
            .status-option:first-child i {
                color: #ffc107;
            }
            
            .status-option:last-child i {
                color: #28a745;
            }
            
            .status-option span {
                font-size: 14px;
                color: #2c3e50;
            }
        </style>`;
        
        // 添加到页面
        $(modalHtml).appendTo('body');
        $(modalStyle).appendTo('head');
        
        // 显示模态框
        $("#workStatusModal").modal('show');
        
        // 添加选项点击事件
        $(".status-option").on('click', function() {
            $(".status-option").removeClass('active');
            $(this).addClass('active');
        });
        
        // 确认按钮点击事件
        $("#confirmStatusChange").on('click', function() {
            var status = $(".status-option.active").data('status');
            
            Fast.api.ajax({
                url: 'order/updateWorkStatus',
                type: 'POST',
                data: {
                    id: id,
                    status: status
                }
            }, function(data, ret) {
                // 添加更明显的成功提示
                Toastr.success('工单状态已成功更新为：' + status);
                
                // 关闭模态框
                $("#workStatusModal").modal('hide');
                
                // 刷新表格
                $("#table").bootstrapTable('refresh');
                return false;
            });
        });
    };
    
    return Controller;
});